﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Sunlit.House.Helper
{
    public class WXBizDataCrypt
    {
        private string _appId = "";
        private string _sessionKey = "";
        public WXBizDataCrypt(string appid ,string sessionKey)
        {
            _appId = appid;
            _sessionKey = sessionKey;
        }
        public string DecryptData(string encryptData,string iv)
        {
            using (RijndaelManaged myRijndael = new RijndaelManaged())
            {
                myRijndael.Key = Convert.FromBase64String(_sessionKey);//UTF8Encoding.UTF8.GetBytes(_sessionKey);
                myRijndael.IV = Convert.FromBase64String(iv);//UTF8Encoding.UTF8.GetBytes(iv);
                myRijndael.Mode = CipherMode.CBC;
                myRijndael.Padding = PaddingMode.PKCS7;

                byte[] toEncryptArray = Convert.FromBase64String(encryptData);

                // Create a decryptor to perform the stream transform.
                ICryptoTransform decryptor = myRijndael.CreateDecryptor();

                byte[] resultArray = decryptor.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);


                string plainText = UTF8Encoding.UTF8.GetString(resultArray);

                dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(plainText);
                if (json.watermark.appid !=_appId)
                {
                    throw new Abp.UI.UserFriendlyException("AppId错误");
                }
                return plainText;
            }
        }
        public string Encrypt(string encryptStr,string iv)
        {
            using (RijndaelManaged myRijndael = new RijndaelManaged())
            {
                myRijndael.Key = Convert.FromBase64String(_sessionKey);//UTF8Encoding.UTF8.GetBytes(_sessionKey);
                myRijndael.IV = Convert.FromBase64String(iv);//UTF8Encoding.UTF8.GetBytes(iv);
                myRijndael.Mode = CipherMode.CBC;
                myRijndael.Padding = PaddingMode.PKCS7;

                byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(encryptStr);
                // Create a decryptor to perform the stream transform.
                ICryptoTransform decryptor = myRijndael.CreateDecryptor();

                byte[] resultArray = decryptor.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);


                return Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
        }
    }
}
